package org.JWCB.system.service.file.impl;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.JWCB.common.core.enums.ResultCode;
import org.JWCB.common.core.exception.ServiceException;
import org.JWCB.common.file.domain.OSSResult;
import org.JWCB.common.file.service.OSSService;
import org.JWCB.system.service.file.IFileService;
import org.JWCB.system.utils.FileValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class FileService implements IFileService {

    @Value("${file.oss.questionTmpDir}")
    private String questionTmpDir;


    @Value("${file.oss.questionFinallyDir}")
    private String questionFinallyDir;
    @Autowired
    private OSSService ossService;

    @Value("${file.oss.downloadUrl}")
    private String downloadUrl;



    private static final Pattern VIDEO_PATTERN = Pattern.compile("<video[^>]*src=\"([^\"]*)\"[^>]*>");
    private static final Pattern IMG_PATTERN = Pattern.compile("<img[^>]*src=\"([^\"]*)\"[^>]*>");


    @Override
    public OSSResult tmpImgUpload(MultipartFile file){
        try {
            FileValidationUtils.imageFileValid(file);
            OSSResult ossResult = ossService.uploadFile(file, questionTmpDir);
            ossResult.setName(downloadUrl + questionTmpDir + ossResult.getName());
            return ossResult;
        } catch (Exception e) {
            log.error("file upload error : ", e);
            throw new RuntimeException(e);
        }

    }


    @Override
    public String transferTempFiles(String questionDesc) {
        if (StrUtil.isEmpty(questionDesc)) {
            return questionDesc;
        }

        // 处理图片文件
        Matcher imgMatcher = IMG_PATTERN.matcher(questionDesc);
        while (imgMatcher.find()) {
            String tempUrl = imgMatcher.group(1);
            String finalUrl = transferFile(tempUrl);
            questionDesc = questionDesc.replace(tempUrl, finalUrl);
        }

        return questionDesc;
    }

    @Override
    public String transferFile(String tempUrl) {
        try {
            // 从URL中提取文件路径
            String tempPath = tempUrl.substring(tempUrl.indexOf(questionTmpDir));
            String fileName = tempPath.substring(tempPath.lastIndexOf("/") + 1);

            // 构建源路径和目标路径
            String targetKey = questionFinallyDir +  fileName;
            ossService.transferFile(tempPath,targetKey);
            return tempUrl.replace(questionTmpDir, questionFinallyDir);
        } catch (Exception e) {
            log.error("文件转储失败: {}", tempUrl, e);
            throw new ServiceException(ResultCode.FAILED_FILE_UPLOAD);
        }
    }

}
